package com.study.lxy.zookeeper;

import com.study.lxy.zookeeper.utils.consts.CommonConsts;
import com.study.lxy.zookeeper.watcher.RealTimeConfigWatcher;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.util.Properties;

public class RealTimeConfigUtils {

    private static final Logger logger = LoggerFactory.getLogger(RealTimeConfigUtils.class);
    private static volatile RealTimeConfigUtils realTimeConfigUtils;

    private volatile Properties properties;

    private RealTimeConfigUtils() {

    }

    public static RealTimeConfigUtils getInstances() {
        if (realTimeConfigUtils == null) {
            synchronized (RealTimeConfigUtils.class) {
                if (realTimeConfigUtils == null) {
                    realTimeConfigUtils = new RealTimeConfigUtils();
                }
            }
        }
        return realTimeConfigUtils;
    }

    public String getValue(String key, String defaultVal) {
        if (properties == null || StringUtils.isEmpty(properties.getProperty(key))) {
            return defaultVal;
        }
        return properties.getProperty(key);
    }

    public synchronized void load() {
        try {
            ZooKeeper zooKeeper = ZookeeperClient.connect(CommonConsts.ZOOKEEPER_URL, 5000);
            byte[] bytes = zooKeeper.getData(CommonConsts.REAL_TIME_PROPERTIES_PATH, new RealTimeConfigWatcher(), new Stat());
            Properties p = new Properties();
            p.load(new ByteArrayInputStream(bytes));
            this.properties = p;
            logger.info("load properties = {}", properties);
        } catch (Exception e) {
            logger.error("load properties error.", e);
        }
    }
}
